package com.hsq.commons.util;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;


public class VmObjectDirective extends Directive {

	@Override
	public String getName() {
		return "vlObj";
	}

	@Override
	public int getType() {
		return BLOCK;
	}

	@Override
	public boolean render(InternalContextAdapter context, Writer w, Node node)
			throws IOException, ResourceNotFoundException, ParseErrorException,
			MethodInvocationException {

		 Object o = node.jjtGetChild(0).value(context);   
		 String field = (String)node.jjtGetChild(1).value(context);   
		 int isHtml = (Integer)node.jjtGetChild(2).value(context);   

		 String[] fields = field.split(",");
		 
		 Node body = node.jjtGetChild(3);  
		 StringWriter sw = new StringWriter();       
		 body.render(context, sw); 
		 String htmls = sw.toString();
		 
		 StringBuffer buff = new StringBuffer();
		 try {
			 for(int i=0;i<fields.length;i++){
				String vString = BeanUtils.getProperty(o, fields[i]);
				htmls = htmls.replaceAll("\\{"+i+"\\}", vString);
			 }
			 if(isHtml==1){
				 htmls = htmls.replaceAll("\\{a\\}", BeanUtils.getProperty(o, "staticUrl"));
			 }else{
				 htmls = htmls.replaceAll("\\{a\\}", BeanUtils.getProperty(o, "dynamicUrl"));
			 }
			 buff.append(htmls);
		 } catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		 System.out.println("isHtml:"+isHtml);
		 System.out.println(buff.toString());
		 w.write(buff.toString());
		 w.flush();
		 w.close();
		 w = null;
		return true;
	}

}
